package com.lapelittle.order.service;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.lapelittle.order.entity.SaleOrder;
import com.lapelittle.order.mapper.SaleOrderMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class SaleOrderImportService {
    private static final Logger logger = LoggerFactory.getLogger(SaleOrderImportService.class);
    
    @Autowired
    private SaleOrderMapper saleOrderMapper;
    
    @Transactional(rollbackFor = Exception.class)
    public void importExcel(MultipartFile file) throws IOException {
        EasyExcel.read(file.getInputStream(), SaleOrder.class, new ReadListener<SaleOrder>() {
            private List<SaleOrder> list = new ArrayList<>();
            
            @Override
            public void invoke(SaleOrder order, AnalysisContext context) {
                list.add(order);
                if (list.size() >= 100) {
                    saveData();
                }
            }
            
            @Override
            public void doAfterAllAnalysed(AnalysisContext context) {
                saveData();
            }
            
            private void saveData() {
                if (!list.isEmpty()) {
                    for (SaleOrder order : list) {
                        SaleOrder existingOrder = saleOrderMapper.findByOrderNo(order.getOrderNo());
                        if (existingOrder != null) {
                            saleOrderMapper.update(order);
                        } else {
                            saleOrderMapper.insert(order);
                        }
                    }
                    logger.info("成功处理{}条数据", list.size());
                    list.clear();
                }
            }
        }).sheet().doRead();
    }
} 